package com.zmn.oms.zmn.business.impl.work;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.google.common.collect.Maps;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.file.FileTypeUtil;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.oms.common.utils.HttpUtil;
import com.zmn.oms.zmn.business.interfaces.work.OrderWorkUploadService;
import com.zmn.tapi.common.aliyun.sts.AccessKeyInfo;
import com.zmn.tapi.dubbo.interfaces.aliyun.OssRemoteService;
import com.zmn.tapi.dubbo.interfaces.api.dependency.FileUploadService;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Calendar;
import java.util.Map;

@Service
public class OrderWorkUploadServiceImpl implements OrderWorkUploadService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @DubboReference(version = com.zmn.tapi.dubbo.DubboConsts.INTERFACE_VERSION, check = false)
    private FileUploadService fileUploadService;
    @Reference(version = com.zmn.tapi.dubbo.DubboConsts.INTERFACE_VERSION, check = false)
    private OssRemoteService ossRemoteService;

    @NacosValue(value = "${order.upload.image.url:http://dev-tapi.xiujiadian.com/api/file/uploadImage}", autoRefreshed = true)
    private String uploadImageSrc;

    @NacosValue(value = "${order.upload.file.url:http://dev-tapi.xiujiadian.com/api/file/uploadFile}", autoRefreshed = true)
    private String uploadFileSrc;

    @Override
    public String uploaderImage(MultipartFile file, String name, String path) throws FileUploadException {
        String fileExtension;
        try {
            if (StringUtil.isNotBlank(path) && path.startsWith("/")) {
                path = path.substring(1);
            }
            fileExtension = FileTypeUtil.getType(file.getInputStream()).getFileExtension();
            ResponseDTO<AccessKeyInfo> accessKeyInfoResponseDTO = ossRemoteService.applyAccessKey("oms", "");
            Map<String, String> otherParam = Maps.newHashMap();
            AccessKeyInfo accessKeyInfo = accessKeyInfoResponseDTO.getData();
            otherParam.put("accessKeyId", accessKeyInfo.getAccessKeyId());
            otherParam.put("securityToken", accessKeyInfo.getSecurityToken());
            otherParam.put("accessKeySecret", accessKeyInfo.getAccessKeySecret());
            otherParam.put("directory", path);
            otherParam.put("fileName", name + fileExtension);
            return uploadFile(uploadImageSrc, file, otherParam);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new FileUploadException(e.getMessage());
        }
    }

    @Override
    public String uploaderImage(MultipartFile file, String path) throws FileUploadException {

        long times = Calendar.getInstance().getTimeInMillis();
        String randomCharAndNumr = StringUtil.getRandomCharAndNumr(5);
        String fileName = getFileName("oms" + times + randomCharAndNumr);

        return uploaderImage(file, fileName, path);
    }

    @Override
    public String uploaderFile(MultipartFile file, String path) throws FileUploadException {
        long times = Calendar.getInstance().getTimeInMillis();
        String randomCharAndNumr = StringUtil.getRandomCharAndNumr(5);
        String fileName = getFileName("oms" + times + randomCharAndNumr);
        return uploaderFile(file, fileName, path);
    }

    @Override
    public String uploaderFile(MultipartFile file, String name, String path) throws FileUploadException {
        try {
            String[] nameArr = file.getOriginalFilename().split("\\.");
            if (nameArr == null || nameArr.length != 2) {
                throw new IOException();
            }
            if (StringUtil.isNotBlank(path) && path.startsWith("/")) {
                path = path.substring(1);
            }
            ResponseDTO<AccessKeyInfo> accessKeyInfoResponseDTO = ossRemoteService.applyAccessKey("oms", "");
            Map<String, String> otherParam = Maps.newHashMap();
            AccessKeyInfo accessKeyInfo = accessKeyInfoResponseDTO.getData();
            otherParam.put("accessKeyId", accessKeyInfo.getAccessKeyId());
            otherParam.put("securityToken", accessKeyInfo.getSecurityToken());
            otherParam.put("accessKeySecret", accessKeyInfo.getAccessKeySecret());
            otherParam.put("directory", path);
            otherParam.put("fileName", name);
            return uploadFile(uploadFileSrc, file, otherParam);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new FileUploadException(e.getMessage());
        }
    }

    /**
     * 使用httpclint 发送文件
     *
     * @param url
     * @param file
     * @param otherParams
     * @return
     */
    public String uploadFile(String url, MultipartFile file, Map<String, String> otherParams) throws Exception {
        HttpClient httpClient = url.matches("https(.*)") ? HttpUtil.getHttpsClient() : HttpUtil.getHttpClient();;
        String result = "";
        HttpResponse response = null;
        try {
            String fileName = file.getOriginalFilename();
            HttpPost httpPost = new HttpPost(url);
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.setCharset(Charset.forName("utf-8"));
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            builder.addBinaryBody("file", file.getInputStream(), ContentType.MULTIPART_FORM_DATA, fileName);
            for (Map.Entry<String, String> e : otherParams.entrySet()) {
                builder.addTextBody(e.getKey(), e.getValue());
            }
            HttpEntity entity = builder.build();
            httpPost.setEntity(entity);
            response = httpClient.execute(httpPost);
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                // 将响应内容转换为字符串
                result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));
                logger.info("#OrderWorkUploadServiceImpl#uploadFile 出参:{}", result);
                Map<String, String> params = JSONObject.parseObject(result, new TypeReference<Map<String, String>>() {
                });
                params = JSONObject.parseObject(params.get("data"), new TypeReference<Map<String, String>>() {
                });
                return params.get("url");
            }
        } finally {
            if (response != null) {
                // 会自动释放连接
                EntityUtils.consume(response.getEntity());
            }
        }
        return result;
    }
}
